package com.ant.collect.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import com.ant.collect.common.ResultCode;
import com.ant.collect.dto.CompanyDto;
import com.ant.collect.handler.AntException;
import com.ant.collect.mapper.CompanyMapper;
import com.ant.collect.mapper.UserMapper;
import com.ant.collect.pojo.Company;
import com.ant.collect.pojo.User;
import com.ant.collect.service.ICompanyService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hzd
 * @since 2025-10-23
 */
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements ICompanyService {

    @Resource
    UserMapper userMapper;

    @Override
    @Transactional
    public Company saveCompany(CompanyDto dto) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", dto.getContactTel());
        User one = userMapper.selectOne(wrapper);
        if (one != null) {
            throw new AntException(ResultCode.FAILURE.getResultCode(), "该用户已存在");
        }

        QueryWrapper<Company> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("company_code", dto.getCompanyCode());
        Company one1 = baseMapper.selectOne(wrapper1);
        if (one1 != null) {
            throw new AntException(ResultCode.FAILURE.getResultCode(), "该公司已存在");
        }

        User user = new User();
        user.setUserName(dto.getContactTel());
        // 默认密码 6个0
        String encryptedPassword = BCrypt.hashpw(dto.getPassword(), BCrypt.gensalt(12));
        user.setUserPwd(encryptedPassword);
        user.setReview(1);
        user.setCreationTime(LocalDateTime.now());
        user.setAccountType(2);
        user.setIsOpen(1);
        userMapper.insert(user);

        Company company = new Company();
        company.setUserId(user.getId());
        company.setProvince("四川省");
        company.setCity(dto.getCity());
        company.setCounty(dto.getCounty());
        company.setAddress(dto.getAddress());
        company.setCompanyCode(dto.getCompanyCode());
        company.setCompanyName(dto.getCompanyName());
        company.setBusinessUrl(dto.getBusinessUrl());
        company.setPersonName(dto.getPersonName());
        company.setPersonUrl(dto.getPersonUrl());
        company.setContact(dto.getContact());
        company.setContactTel(dto.getContactTel());
        company.setEmail(dto.getEmail());
        company.setReview(1);
        company.setEnterpriseType(dto.getEnterpriseType());
        company.setCreationTime(new Date());
        baseMapper.insert(company);
        return company;
    }

    /**
     * 生成用户初始密码（8位字母+数字）
     */
    public String generateInitialPwd() {
        return RandomStringUtils.randomAlphanumeric(8);
    }

    /*
    @return 验证码
     */
    public static String generateClearCode() {
        // 排除容易混淆的字符，只保留清晰易认的
        String chars = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz";
        return RandomStringUtils.random(8, chars);
    }

    public static void main(String[] args){
        //String encryptedPassword = BCrypt.hashpw("wg7131476!", BCrypt.gensalt(12));
        //System.out.println(encryptedPassword);
        String str = "avbb dfdc ";
        String trim = str.replaceAll("\\s", "");
        System.out.println( trim);
    }

    @Override
    public Map<String, Object> queryCompanyList(CompanyDto dto) {
        try {
            Page<Company> pageInfo = new Page<>(dto.getPageIndex(), dto.getPageSize());
            QueryWrapper<Company> wrapper = new QueryWrapper<>();
            if (!ObjectUtils.isEmpty(dto.getCompanyName())) {
                wrapper.eq("company_name", dto.getCompanyName().trim());
            }
            wrapper.orderByDesc("id");
            Page<Company> list = baseMapper.selectPage(pageInfo, wrapper);
            List<Company> companyList = list.getRecords();
            companyList.stream().forEach(item -> {
                item.setUser(userMapper.selectOne(new QueryWrapper<User>().eq("id", item.getUserId())));
            });
            Map<String, Object> map = new HashMap<>();
            map.put("list", companyList);
            map.put("total", list.getTotal());
            return map;
        } catch (Exception e) {
            throw new AntException(ResultCode.BODY_NOT_MATCH);
        }

    }

    @Override
    public void findApprovedById(Integer id, Integer status) {
        Company company = new Company();
        company.setId(id);
        company.setReview(status);
        Integer userId = StpUtil.getLoginIdAsInt();
        company.setReviewName(userId.toString());
        company.setReviewTime(new Date());
        baseMapper.updateById(company);
    }
}
